# coding=utf-8
# save stock finance
# 没必要单独执行，应当使用snatchStockPepb.py
import psycopg2
from wddb import initDb
import os
from htmlUtil import downHTML
from stockCommon import readStockCodes
from pyquery import PyQuery as pq

financeUrl=r"http://quotes.money.163.com/f10/zycwzb_%s.html"
#pepbUrl=r"http://stockpage.10jqka.com.cn/realHead_v2.html#hs_%s"

def readTrValue(tr):
    tds = pq(tr)('td')
    s = pq(tds[0]).text()
    return s
def getStockFinanceFromHtml(html):
    #print(html)
    if html=='' or html==None :
        return None
    doc = pq(html)
    trs=doc(".col_r table tr")
    f={}
    #每股收益
    idx=1
    s=readTrValue(trs[idx])
    try:
        f["eps"]=float(s)
    except:
        f["eps"]=0
    return f


def getStockFinance(code):
    u=financeUrl%(code)
    print(u)
    html=downHTML(u)
    if u=="" :
        return None
    f=getStockFinanceFromHtml(html)
    if f==None:
        return None
    #u=pepbUrl%(code)
    #html=downHTML(u)
    #f2=getPePbFromHtml(html)
    #f["pe"]=f2["pe"]
    #f["pb"]=f2["pb"]
    f["code"]=code
    return f
def saveFinanceToDb(con,finance):
    pass

def main():
    con=initDb()
    codes=readStockCodes(con)
    for c in codes:
        f=getStockFinance(c)
        if(f!=None):
            print(f)
            saveFinanceToDb(con,f)
    con.close()

if __name__=="__main__":
    main()